﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Ordering.Domain.SeedWork;

namespace Ordering.Infrastructure
{
    public static class MediatorExtensions
    {
        /// <summary>
        /// 发布领域事件
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static async Task DispatchDomainEventsAsync(this IMediator mediator, DbContext context)
        {
            var entities = context.ChangeTracker.Entries<Entity>();
            var events = entities
                .SelectMany(s => s.Entity.DomainEvents)
                .ToList();
            entities.ToList().ForEach(e =>
            {
                e.Entity.ClearDomainEvent();
            });
            foreach (var item in events)
            {
                await mediator.Publish(item);
            }
        }
    }
}
